package com.eascs.web.o2o.web.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.o2o.web.form.OverdualForm;
import com.eascs.web.o2o.web.form.OverdualStatForm;
import com.eascs.web.o2o.web.form.ReportStatForm;
import com.eascs.web.o2o.web.service.OverdualReportService;
import com.eascs.web.o2o.web.util.ExcelParser;
import com.eascs.web.o2o.web.util.ExcelType;

@RestController
@RequestMapping("/overdualRest")
public class OverdualReportRestController {

	private static Logger log = LoggerFactory.getLogger(OverdualReportRestController.class);

	@Autowired
	OverdualReportService overdualReportService;
	
	@Value("${web.homeUrl}")
	private String adminUrl;
	@SuppressWarnings("unused")
	@RequestMapping("/report")
	public PaginationRestResult report(OverdualForm vo) {
		String o2ourl = "/overdualRest/report";
		vo.setPageSize(10);
		PageResult<Object[]> pageResult = overdualReportService.getOverdualReportByPage(vo);
		String[] oatitles = { "贷款编号", "经营单位", "借款人姓名",  "放款银行", "放款金额(元)",  "到期日期", "处置状态","处置时间","拖欠总额(元)", "逾期本金(元)", "逾期利息(元)", "罚息合计(元)", "处置金额(元)","统计时间" };
		SelectDataOption[] selectDataOptions = { null, null, null, null, null, null,new SelectDataOption("OTO_OVERDUE_STATUS"), null, null, null, null, null, null, null };
		if (vo != null) {
			o2ourl = UrlUtil.appendUrl(o2ourl, "billCode", vo.getBillCode());
			o2ourl = UrlUtil.appendUrl(o2ourl, "refundBank", vo.getRefundBank());
			o2ourl = UrlUtil.appendUrl(o2ourl, "status", vo.getStatus());
			o2ourl = UrlUtil.appendUrl(o2ourl, "province", vo.getProvince());
			o2ourl = UrlUtil.appendUrl(o2ourl, "loanName", vo.getLoanName());
			o2ourl = UrlUtil.appendUrl(o2ourl, "ltd", vo.getLtd());
			o2ourl = o2ourl + "&pageIndex=";
		} else {
			o2ourl = o2ourl + "?pageIndex=";
		}
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, oatitles, o2ourl);
		Button[] titleButton = new Button[] { ButtonHelper.createRedirectButton(null, adminUrl+"/afterloan/detail?billCode=") };
		paginationInfo.setTitleButtons(titleButton);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(0);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setRendTo("#oa_result");
		paginationInfo.setFormats(new Format[] { null, null, null, null, new DecimalFormat(",##0.00"), null, null, null,new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), null });
		ViewContext.put("vo", vo);
		ViewContext.put("paginationInfo", paginationInfo);
		return PaginationRestResult.buildPaginationRestResult(paginationInfo);
	}

	//根据平台查询逾期报表
  	@RequestMapping("/overdualPlatform")
  	public PaginationRestResult overdualPlatform(OverdualStatForm entity) {
  		String o2ourl = "/overdualRest/overdualPlatform";
  		
  		
  		if (entity != null) {
  			String province = entity.getProvince() == null ? "" : entity.getProvince();
  			o2ourl = UrlUtil.appendUrl(o2ourl, "province", province);
  			o2ourl = o2ourl + "&o2oIndex=";
  		} else {
  			o2ourl = o2ourl + "?o2oIndex=";
  		}
  		entity.setPageSize(10000);
  		PageResult<Object[]> pageResult = overdualReportService.getOverdualReportStatByPlatformByPage(entity);
  		
  		List<Object[]> data  = pageResult.getData();
  		String titles[] = { "省区", "经办平台", "累计放款笔数", "累计放款金额（元）","正常余额笔数","正常余额金额（元）","逾期余额笔数","逾期余额金额（元）","利息逾期笔数","利息逾期金额（元）","罚息笔数","罚息金额（元）","报告期已代偿余额笔数","报告期已代偿余额金额（元）"};
  		SelectDataOption[] selectDataOptions = { null, null, null,null, null, null, null, null, null, null, null};
  		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles, o2ourl);
  		o2oPagingInfo.setBuildPagingNavigation(false);
  		o2oPagingInfo.setFirstRenderColumnIndex(0);
  		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
  		o2oPagingInfo.setFormats(new Format[] { null, null, null, new DecimalFormat(",##0.00"), null, new DecimalFormat(",##0.00"), null,  new DecimalFormat(",##0.00"),null, new DecimalFormat(",##0.00"), null , new DecimalFormat(",##0.00"), null , new DecimalFormat(",##0.00")});
  		o2oPagingInfo.setRendTo("#o2o_result");
  		ViewContext.put("vo", entity);
  		return PaginationRestResult.buildPaginationRestResult(o2oPagingInfo);
  	}
  	
  //根据省区查询逾期报表
  	@RequestMapping("/overdualProvince")
  	public PaginationRestResult overdualProvince(OverdualStatForm entity) {
  		String o2ourl = "/overdualRest/overdualProvince";
  		
  		
  		if (entity != null) {
  			String province = entity.getProvince() == null ? "" : entity.getProvince();
  			o2ourl = UrlUtil.appendUrl(o2ourl, "province", province);
  			o2ourl = o2ourl + "&o2oIndex=";
  		} else {
  			o2ourl = o2ourl + "?o2oIndex=";
  		}
  		entity.setPageSize(10000);
  		PageResult<Object[]> pageResult = overdualReportService.getOverdualReportStatByProvinceByPage(entity);
  		
  		List<Object[]> data  = pageResult.getData();
  		String titles[] = { "省区", "累计放款笔数", "累计放款金额（元）","正常余额笔数","正常余额金额（元）","逾期余额笔数","逾期余额金额（元）","利息逾期笔数","利息逾期金额（元）","罚息笔数","罚息金额（元）","报告期已代偿余额笔数","报告期已代偿余额金额（元）"};
  		SelectDataOption[] selectDataOptions = { null, null,null, null, null, null, null, null, null, null};
  		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles, o2ourl);
  		o2oPagingInfo.setBuildPagingNavigation(false);
  		o2oPagingInfo.setFirstRenderColumnIndex(0);
  		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
  		o2oPagingInfo.setFormats(new Format[] { null, null, new DecimalFormat(",##0.00"), null, new DecimalFormat(",##0.00"), null,  new DecimalFormat(",##0.00"),null, new DecimalFormat(",##0.00"), null , new DecimalFormat(",##0.00"), null , new DecimalFormat(",##0.00")});
  		o2oPagingInfo.setRendTo("#o2o_result");
  		ViewContext.put("vo", entity);
  		return PaginationRestResult.buildPaginationRestResult(o2oPagingInfo);
  	}
	
  	@RequestMapping("/toImport")
	public HtmlRestResult toImport() {
		return HtmlRestResult.popHtmlFragment("overdual/import_overdueReport");
	}

	/**
	 * 预期报表导入 刷新
	 * @param file
	 * @param billCode
	 * @param loanerName
	 * @param idNum
	 * @return
	 */
	@RequestMapping("/uploadExecl")
	public BaseRestResult<String> uploadExcel(@RequestParam(value = "file", required = false) MultipartFile file, String billCode,String loanerName,String idNum) {
		@SuppressWarnings("unused")
		InputStream inputStream = null;
		try {
			inputStream = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		ExcelType[] types = new ExcelType[] {//验证excel数据是否正确
				new ExcelType(ExcelType.CELL_TYPE_STRING, true),//1
				new ExcelType(ExcelType.CELL_TYPE_STRING, true),//2
				new ExcelType(ExcelType.CELL_TYPE_NUMERIC, true),//3
				new ExcelType(ExcelType.CELL_TYPE_NUMERIC, true),//4
				new ExcelType(ExcelType.CELL_TYPE_NUMERIC, true),//5
				new ExcelType(ExcelType.CELL_TYPE_NUMERIC, true),//6
				new ExcelType(ExcelType.CELL_TYPE_STRING, true),//7
				new ExcelType(ExcelType.CELL_TYPE_STRING, true),//8
				new ExcelType(ExcelType.CELL_TYPE_NUMERIC, true),//9
				new ExcelType(ExcelType.CELL_TYPE_DATE, true),//10
				new ExcelType(ExcelType.CELL_TYPE_DATE, true)//11
		};
		
		long beginTime = System.currentTimeMillis();
		ExcelParser parser = new ExcelParser(types);
		try {
			parser.run(file.getInputStream());
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		List<Object> errorresults = parser.getErrorresults();
		StringBuffer error = new StringBuffer();
		for (int i = 0; i < errorresults.size(); i++) { //如果数据格式有问题，先打出loger 
			//return BaseRestResult.info("导入成功");
			error.append("导入数据有误请检查：错误数据位置为："+(String) errorresults.get(i)+"\r\n");
			log.error("error.excel.read", (String) errorresults.get(i));
		}
		if(error!=null&&StringUtils.isNotBlank(error)){
			return BaseRestResult.warn(error.toString());
		}
		List<List<Object>> results = parser.getResults();  //解析出来的数据
		//循环去查询表插入逾期报表
		
		log.info(new StringBuilder().append("耗时：").append(
				(System.currentTimeMillis() - beginTime)).append(
				",导入记录数：").append(results.size()).append(
				",批量导入级别-导入Excel").toString());
		
		BaseRestResult<String> infoResults=overdualReportService.addList(results);
		
		return infoResults;
		
	/*	try {
			ExcelApiHelper.readHandle(inputStream, new RowReadHandler() {
				@Override
				public void handle(int sheetIndex, int rowIndex, Object[] rowDatas) {
					check(sheetIndex, rowIndex, rowDatas, 0, billCode,loanerName,idNum);
				}
			});
		} catch (RuntimeException e) {
			String message = e.getMessage();
			message = e.getMessage().substring(27, message.length());
			return BaseRestResult.warn(message);
		}
		InputStream inputStream1 = null;
		try {
			inputStream1 = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			ExcelApiHelper.readHandle(inputStream1, new RowReadHandler() {
				@Override
				public void handle(int sheetIndex, int rowIndex, Object[] rowDatas) {
					check(sheetIndex, rowIndex, rowDatas, 1, billCode,loanerName,idNum);
				}
			});

		} catch (RuntimeException e) {
			String message = e.getMessage();
			message = e.getMessage().substring(27, message.length());
			return BaseRestResult.warn(message);

		}*/
		//return BaseRestResult.buildClosestReloadResult();
	}
	
	@RequestMapping("/download")
	public BaseRestResult<String> dowanload(HttpServletResponse httpServletResponse, HttpServletRequest request) {
		BaseRestResult<String> result = null;
		String file = MonReportRestController.class.getResource("/excelTemplate/overdueReport.xls").getPath();

		OutputStream os = null;
		try {
			String outfile = "overdueReport.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(file);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
		return result;
	}
}
